package com.example.aigc_education.ws;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.aigc_education.integration.request.ChatMessageRequestV2;
import com.example.aigc_education.rpc.api.v2.ChatServiceProto;
import com.example.aigc_education.utils.JsonUtils;
import com.example.aigc_education.utils.WebSocketUtils;
import com.example.aigc_education.ws.handler.MessageHandler;
import com.example.aigc_education.ws.handler.MessageHandlerFactory;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;

@Slf4j
public class WebSocketEventListener implements StreamObserver<ChatServiceProto.ChatMessage> {

    private WebSocketSession webSocketSession;

    public WebSocketEventListener(WebSocketSession webSocketSession) {
        this.webSocketSession = webSocketSession;
    }

    @Override
    public void onNext(ChatServiceProto.ChatMessage chatMessage) {

        log.info("[WebSocketEventListener] onNext sessionId: {}, chatMessage: {}", webSocketSession.getId(), chatMessage.getContentsList());

        // text = 0, image_url = 1, input_audio = 2, video_url = 3, file_object = 4, topic_card = 5, collapse_start = 6, collapse_end = 7, single_select = 8, map = 9, link = 10
        // 使用工厂获取适合的处理器并处理消息
        MessageHandler handler = MessageHandlerFactory.getHandler(chatMessage);
        ChatMessageRequestV2 response = handler.handle(chatMessage);

        WebSocketUtils.sendMessage(webSocketSession, JsonUtils.toJson(response));
    }

    @Override
    public void onError(Throwable throwable) {
        log.error("[WebSocketEventListener] onError sessionId: {}, exception msg: {}", webSocketSession.getId(), throwable);
    }

    @Override
    public void onCompleted() {
        log.info("[WebSocketEventListener] onCompleted sessionId: {}", webSocketSession.getId());
    }
}
